package com.cn.xiaonuo.tcrfinance.tcrusers.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.core.context.login.LoginContext;
import com.cn.xiaonuo.core.pojo.login.SysLoginUser;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserHpcMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvLoginUser;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvWallet;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvLoginUserMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvWalletMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.service.LoginService;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class LoginServiceImpl extends ServiceImpl<PvLoginUserMapper, PvLoginUser> implements LoginService {

    @Resource
    private PvLoginUserMapper pvLoginUserMapper;

    @Autowired
   private Environment env;
    @Resource
    private PvWalletMapper pvWalletMapper;
    @Autowired
    private LoginContext loginContext;
    @Autowired
    private SysUserHpcMapper sysUserHpcMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage userRegister(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            String phone = (String) params.get("phone");
            String pwdo = (String) params.get("pwdo");
            String pwdt = (String) params.get("pwdt");
//            String noteNum = (String) params.get("noteNum");
            if (StringUtils.isBlank(phone)) {
                message.setMessage("注册手机号不能为空");
                return message;
            }
            PvLoginUser loginUser = pvLoginUserMapper.selectOne(new QueryWrapper<>(new PvLoginUser(){{
                setPhone(phone);
            }}));
            if (null != loginUser) {
                message.setMessage("该手机已注册，请勿重复注册");
                return message;
            }
            if (StringUtils.isBlank(pwdo) | StringUtils.isBlank(pwdt)) {
                message.setMessage("注册初始密码不能为空");
                return message;
            }
            if (StringUtils.isNotBlank(pwdo) && StringUtils.isNotBlank(pwdt)) {
                if (!(pwdo.equals(pwdo))) {
                    message.setMessage("输入密码不一致");
                    return message;
                }
            }
//            smsPasswordCache.evict(phone);
            PvLoginUser pvLoginUser = new PvLoginUser() {{
                setPhone(phone);
                setPassword(pwdo);
            }};

            pvLoginUser.setStatus(Short.valueOf("0"));
            pvLoginUserMapper.insert(pvLoginUser);
            Integer resultid = pvLoginUser.getId();
            String accountNum = "688";
            if (null != resultid) {
                if (resultid > 0 && resultid <= 9) {
                    accountNum = accountNum + ("00000") + (resultid);
                } else if (resultid >= 10 && resultid < 99) {
                    accountNum = accountNum + ("0000") + (resultid);
                } else if (resultid >= 100 && resultid < 999) {
                    accountNum = accountNum + ("000") + (resultid);
                } else if (resultid >= 1000 && resultid < 9999) {
                    accountNum = accountNum + ("00") + (resultid);
                } else if (resultid >= 10000 && resultid < 99999) {
                    accountNum = accountNum + ("0") + (resultid);
                } else if (resultid >= 100000 && resultid < 999999) {
                    accountNum = accountNum + (resultid);
                } else {
                    accountNum = accountNum + (resultid);
                }
            }
            String province = this.getProvince(phone);
            pvLoginUser.setProvNum(province);
            pvLoginUser.setAccounts(String.valueOf(accountNum));
            pvLoginUser.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            pvLoginUserMapper.updateById(pvLoginUser);//注册根据id设置账号
            //注册成功默认创建一个钱包
            PvWallet wallet = new PvWallet();
            wallet.setUserId(resultid);
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            wallet.setCreateTime(currentTime);
            pvWalletMapper.insert(wallet);
            message.setSuccess(true);
            message.setMessage("注册成功");
            //注册成功发送短信
//            String[] paramss = {pvLoginUser.getAccounts()};//短信动态添加的内容
//            TencentSmsUtils.smsSingleSender(SmsConstant.appid, SmsConstant.appkey, "86", phone, 471331, paramss, "全球乡村振兴", "", "");

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            e.printStackTrace();
        }
        return message;
    }

    @Override
    public SysUserHpcEntity getCurrentLoginUser() {
        SysUserHpcEntity sysUserHpcEntity=null;
        SysLoginUser obj = loginContext.getSysLoginUser();
        if (Objects.nonNull(obj)) {
            Long clientId = obj.getId();
            if (clientId != null) {
                QueryWrapper<SysUserHpcEntity> user = new QueryWrapper<>(new SysUserHpcEntity() {{
                    setUserId(clientId.longValue());
                }});
                 sysUserHpcEntity = sysUserHpcMapper.selectOne(user);
            }
        } else {
            log.error("识别登录用户信息失败");
        }
        return sysUserHpcEntity;
    }

    public String getProvince(String phone) {
        //API产品路径
        String requestUrl = env.getProperty("alicloudapi.aiphone");
        //阿里云APPCODE
        String appcode =env.getProperty("alicloudapi.appcode");

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("MOBILE_NUMBER", phone);
        String lastResult = "";

        try {
            String response = get(requestUrl, headers, querys);
            //{"INPUT_MOBILE_NUMBER_STRING": "18113011428", "EXTRACT_MOBILE_NUMBER_STRING": "18113011428", "STATUS": "艾科瑞特，让企业业绩长青", "ENTITY": {"MOBILE_NUMBER": "18113011428", "MOBILE_NUMBER_PREFIX": "1811301", "PROVINCE": "四川", "CITY": "成都", "ISP": "中国电信", "AREA_CODE": "028", "POST_CODE": "610000", "ADCODE": "510100", "GPS": "104.066541,30.572269"}}
            lastResult = Convert.toStr(JSON.parseObject(JSON.parseObject(response).get("ENTITY").toString()).get("PROVINCE"));//获取信息详细地址
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null != lastResult ? lastResult : "查询无结果";
    }

    public static String get(String url, Map<String, String> headers, Map<String, String> querys) throws IOException {
        //添加参数
        for (String key : querys.keySet()) {
            url += (key + "=" + URLEncoder.encode(querys.get(key), "utf-8") + '&');
        }
        url = url.substring(0, url.length() - 1);

        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        GetMethod getMethod = new GetMethod(url);
        // 必须设置下面这个Header
        for (String key : headers.keySet()) {
            getMethod.addRequestHeader(key, headers.get(key));
        }

        int code = client.executeMethod(getMethod);
        if (code == 200) {
            String res = getMethod.getResponseBodyAsString();
            System.out.println(res);
            return res;
        }
        throw new IOException("请求失败");
    }
}
